/*!
 * Tpflow Design 流程设计器 V5.0
 * http://cojz8.com
 *
 * 
 * Auth:Guoguo(632522043@qq.com)
 * http://cojz8.com
 *
 * Date: 2020年11月28日21:12:20
 */
var Tpflow = {
	lopen : function(title,url,w,h) {
		if (title == null || title == '') {
				title=false;
			};
			if (w == null || w == '') {
				w=($(window).width());
			};
			if (h == null || h == '') {
				h=($(window).height());
			};
			layer.open({
				type: 2,
				area: [w+'px', h+'px'],
				fix: false, //不固定
				maxmin: true,
				shade:0.4,
				title: title,
				content: url
			});
	},
	lclose : function(title,url,w,h) {
		var index = parent.layer.getFrameIndex(window.name);
		parent.layer.close(index);
	},
	common_return : function(data) {
		if (data.code == 0) {
			layer.msg(data.msg,{icon:1,time: 1500},function(){
					parent.location.reload(); // 父页面刷新
			});          
		} else {
		   layer.alert(data.msg, {title: "错误信息", icon: 2});
		}
	},
	Init : function(processData) {
		_this.append('<input type="hidden" id="wf_active_id" value="0"/>');
		_this.append('<div id="wf_process_info"></div>');
		  var aConnections = [];
		  var setConnections = function(conn, remove) {
			  if (!remove) aConnections.push(conn);
			  else {
				  var idx = -1;
				  for (var i = 0; i < aConnections.length; i++) {
					  if (aConnections[i] == conn) {
						  idx = i; break;
					  }
				  }
				  if (idx != -1) aConnections.splice(idx, 1);
			  }
			  if (aConnections.length > 0) {
				  var s = "";
				  for ( var j = 0; j < aConnections.length; j++ ) {
					  var from = $('#'+aConnections[j].sourceId).attr('process_id');
					  var target = $('#'+aConnections[j].targetId).attr('process_id');
					  s = s + "<input type='hidden' value=\"" + from + "," + target + "\">";
				  }
				  $('#wf_process_info').html(s);
			  } else {
				  $('#wf_process_info').html('');
			  }
			  jsPlumb.repaintEverything();//重画
		  };
		var initEndPoints = function(){
		  $(".process-flag").each(function(i,e) {
			  var p = $(e).parent();
			  jsPlumb.makeSource($(e), {
				  parent:p,
				  anchor:"Continuous",
				  endpoint:[ "Dot", { radius:1 } ],
				  connector:[ "Flowchart", { stub:[5, 5] } ],
				  connectorStyle:{lineWidth:3,strokeStyle:"#49afcd",joinstyle:"round"},
				  hoverPaintStyle:{lineWidth:3,strokeStyle:"#da4f49"},
				  dragOptions:{},
				  maxConnections:-1
			  });
		  });
		}
		jsPlumb.importDefaults({
            DragOptions : { cursor: 'pointer'},
            EndpointStyle : { fillStyle:'#225588' },
            Endpoint : [ "Dot", {radius:1} ],
            ConnectionOverlays : [
                [ "Arrow", { location:1 } ],
                [ "Label", {location:0.1,id:"label",cssClass:"aLabel"}]
            ],
            Anchor : 'Continuous',
            ConnectorZIndex:5,
            HoverPaintStyle:{lineWidth:3,strokeStyle:"#da4f49"}
        });
        if( $.browser.msie && $.browser.version < '9.0' ){ //ie9以下，用VML画图
            jsPlumb.setRenderMode(jsPlumb.VML);
        } else { //其他浏览器用SVG
            jsPlumb.setRenderMode(jsPlumb.SVG);
        }
	 var lastProcessId=0;
	 $.each(processData.list, function(i,row) {
            var nodeDiv = document.createElement('div');
			 var nodeId = "window" + row.id;
            $(nodeDiv).attr("id",nodeId)
            .attr("style",row.style +'text-align: left;')
            .attr("process_to",row.process_to)
            .attr("process_id",row.id)
            .addClass("process-step wf_btn")
            .html('<span class="process-flag" style="text-align: left;"><img src="'+Tpflow.Ico()+'" width=18px></span>&nbsp;' +row.process_name + '<br/><img src="'+Tpflow.Ico(1)+'" width=18px>&nbsp;' +row.mode + '<br/><img src="'+Tpflow.Ico(2)+'" width=18px>&nbsp;' +row.name + '' );
            _this.append(nodeDiv);
            lastProcessId = row.id;
        });
	 var timeout = null;
    //点击或双击事件,这里进行了一个单击事件延迟，因为同时绑定了双击事件
	$(".process-step").live('click',function(){
        _this.find('#wf_active_id').val($(this).attr("process_id")),
        clearTimeout(timeout);
        var obj = this;
		Tpflow.DClick($(this).attr("process_id"));
        timeout = setTimeout(Tpflow.Click(),300);
    }).live('dblclick',function(){
        clearTimeout(timeout);
		Tpflow.DelJProcessData();
    });
	 jsPlumb.draggable(jsPlumb.getSelector(".process-step"),{containment: 'parent'});//允许拖动
	 initEndPoints();
	 jsPlumb.bind("jsPlumbConnection", function(info) {
        setConnections(info.connection)
    });
    //绑定删除connection事件
    jsPlumb.bind("jsPlumbConnectionDetached", function(info) {
       setConnections(info.connection, true);
    });
    //绑定删除确认操作
    jsPlumb.bind("click", function(c) {
      if(confirm("你确定取消连接吗?"))
        jsPlumb.detach(c);
    });
    //连接成功回调函数
    function mtAfterDrop(params){
        defaults.mtAfterDrop({sourceId:$("#"+params.sourceId).attr('process_id'),targetId:$("#"+params.targetId).attr('process_id')});
    }
    jsPlumb.makeTarget(jsPlumb.getSelector(".process-step"), {
        dropOptions:{ hoverClass:"hover", activeClass:"active" },
        anchor:"Continuous",
        maxConnections:-1,
        endpoint:[ "Dot", { radius:1 } ],
        paintStyle:{ fillStyle:"#ec912a",radius:1 },
        hoverPaintStyle:{lineWidth:3,strokeStyle:"#da4f49"},
        beforeDrop:function(params){
            if(params.sourceId == params.targetId) return false;/*不能链接自己*/
            var j = 0;
            $('#wf_process_info').find('input').each(function(i){
                var str = $('#' + params.sourceId).attr('process_id') + ',' + $('#' + params.targetId).attr('process_id');
                if(str == $(this).val()){
                    j++;
                    return;
                }
            })
            if( j > 0 ){
                defaults.fnRepeat();
                return false;
            } else {
                return true;
            }
        }
    });
	$('.process-step').each(function(i){
            var sourceId = $(this).attr('process_id');
            var prcsto = $(this).attr('process_to');
            var toArr = prcsto.split(",");
            $.each(toArr,function(j,targetId){
                if(targetId!='' && targetId!=0){
                    //检查 source 和 target是否存在
                    var is_source = false,is_target = false;
                    $.each(processData.list, function(i,row){
                        if(row.id == sourceId){
                            is_source = true;
                        }else if(row.id == targetId){
                            is_target = true;
                        }
                        if(is_source && is_target)
                            return true;
                    });
                    if(is_source && is_target){
                        jsPlumb.connect({
                            source:"window"+sourceId, 
                            target:"window"+targetId,
							overlays: [["Label", {cssClass: "component label",label: sourceId+" - "+targetId,}],"Arrow"]
                        });
                        return ;
                    }
                }
            })
			
        });
	},
	show : function(processData) {
		_this.append('<input type="hidden" id="wf_active_id" value="0"/>');
		_this.append('<div id="wf_process_info"></div>');
		 
		var initEndPoints = function(){
		  $(".process-flag").each(function(i,e) {
			  var p = $(e).parent();
			  jsPlumb.makeSource($(e), {
				  parent:p,
				  anchor:"Continuous",
				  endpoint:[ "Dot", { radius:1 } ],
				  connector:[ "Flowchart", { stub:[5, 5] } ],
				  connectorStyle:{lineWidth:3,strokeStyle:"#49afcd",joinstyle:"round"},
				  hoverPaintStyle:{lineWidth:3,strokeStyle:"#da4f49"},
				  dragOptions:{},
				  maxConnections:-1
			  });
		  });
		}
		jsPlumb.importDefaults({
            DragOptions : { cursor: 'pointer'},
            EndpointStyle : { fillStyle:'#225588' },
            Endpoint : [ "Dot", {radius:1} ],
            ConnectionOverlays : [
                [ "Arrow", { location:1 } ],
                [ "Label", {location:0.1,id:"label",cssClass:"aLabel"}]
            ],
            Anchor : 'Continuous',
            ConnectorZIndex:5,
            HoverPaintStyle:{lineWidth:3,strokeStyle:"#da4f49"}
        });
        if( $.browser.msie && $.browser.version < '9.0' ){ //ie9以下，用VML画图
            jsPlumb.setRenderMode(jsPlumb.VML);
        } else { //其他浏览器用SVG
            jsPlumb.setRenderMode(jsPlumb.SVG);
        }
	 var lastProcessId=0;
	 $.each(processData.list, function(i,row) {
            var nodeDiv = document.createElement('div');
			 var nodeId = "window" + row.id;
            $(nodeDiv).attr("id",nodeId)
            .attr("style",row.style +'text-align: left;')
            .attr("process_to",row.process_to)
            .attr("process_id",row.id)
            .addClass("process-step wf_btn")
            .html('<span class="process-flag" style="text-align: left;"><img src="'+Tpflow.Ico()+'" width=18px></span>&nbsp;' +row.process_name + '<br/><img src="'+Tpflow.Ico(1)+'" width=18px>&nbsp;' +row.mode + '<br/><img src="'+Tpflow.Ico(2)+'" width=18px>&nbsp;' +row.name + '' );
            _this.append(nodeDiv);
            lastProcessId = row.id;
        });
		initEndPoints();
	$('.process-step').each(function(i){
            var sourceId = $(this).attr('process_id');
            var prcsto = $(this).attr('process_to');
            var toArr = prcsto.split(",");
            $.each(toArr,function(j,targetId){
                if(targetId!='' && targetId!=0){
                    //检查 source 和 target是否存在
                    var is_source = false,is_target = false;
                    $.each(processData.list, function(i,row){
                        if(row.id == sourceId){
                            is_source = true;
                        }else if(row.id == targetId){
                            is_target = true;
                        }
                        if(is_source && is_target)
                            return true;
                    });
                    if(is_source && is_target){
                        jsPlumb.connect({
                            source:"window"+sourceId, 
                            target:"window"+targetId,
							overlays: [["Label", {cssClass: "component label",label: sourceId+" - "+targetId,}],"Arrow"]
                        });
                        return ;
                    }
                }
            })
			
        });
	},
	
	DClick : function(id) {
		var url = Server_Url+"?id="+id+"&act=att";
		$('#iframepage').attr('src',url);
	},
	Api : function(Action) {
		var reload = false;
		switch(Action) {    
			case 'save':
				var PostData = {"flow_id":the_flow_id,"process_info":Tpflow.GetJProcessData()};//获取到步骤信息
				break;
			case 'delAll':
				var PostData = {"flow_id":the_flow_id};
				reload = true;
				break;
			case 'att':
				
				return ;
				break;
			case 'add':
				var PostData = {"flow_id":the_flow_id};
				reload = true;
				break;
			case 'check':
				var PostData = {"flow_id":the_flow_id};
				break;
			case 'Refresh':
				location.reload();return;
				break;
			case 'Help':
				layer.open({
					  type: 2,
					  title: '工作流官网',
					  shadeClose: true,
					  shade: false,
					  maxmin: true, //开启最大化最小化按钮
					  area: ['893px', '600px'],
					  content: '//cojz8.com/'
				});
				break;
			 default:
				
		} 
		var Url = Server_Url+'?act='+Action;
		Tpflow.sPost(Url,PostData,reload);
	},
    wfconfirm : function(url,data,msg) {
		layer.confirm(msg, {
			  btn: ['执行','取消'] //按钮
		}, function(){
			  Tpflow.sPost(url,data);
		}, function(){
			  layer.msg('取消操作', {
				time: 2000, //20s后自动关闭
			  });
		});
	},
	sPost : function(Post_Url,PostData,reload=true) {
		$.post(Post_Url,PostData,function(data){
			if(data.code==0){
				layer.msg(data.msg,{icon:1,time: 1500},function(){
					if(reload){
						location.reload();
					}
				}); 
			}else{
				layer.msg(data.msg, {
				time: 2000, //20s后自动关闭
			  });
				
			}
		},'json');
	},
	DelJProcessData : function(){
		if(confirm("你确定删除步骤吗？")){
			var activeId = _this.find("#wf_active_id").val();//右键当前的ID
			$.post(Server_Url+'?act=del',{"flow_id":the_flow_id,"id":activeId},function(data){
				if(data.status==1){
					 if(activeId>0){
						$("#window"+activeId).remove();
					 }
					Tpflow.Api('save');
				}
				layer.msg(data.msg);
			},'json');
		 }
	},
	Click : function(){
		return 123;
	},
	GetJProcessData : function(){
		try{
              var aProcessData = {};
              $("#wf_process_info input[type=hidden]").each(function(i){
                  var processVal = $(this).val().split(",");
                  if(processVal.length==2)
                  {
                    if(!aProcessData[processVal[0]])
                    {
                        aProcessData[processVal[0]] = {"top":0,"left":0,"process_to":[]};
                    }
                    aProcessData[processVal[0]]["process_to"].push(processVal[1]);
                  }
              })
              _this.find("div.process-step").each(function(i){ //生成Json字符串，发送到服务器解析
                      if($(this).attr('id')){
                          var pId = $(this).attr('process_id');
                          var pLeft = parseInt($(this).css('left'));
                          var pTop = parseInt($(this).css('top'));
                         if(!aProcessData[pId])
                          {
                              aProcessData[pId] = {"top":0,"left":0,"process_to":[]};
                          }
                          aProcessData[pId]["top"] =pTop;
                          aProcessData[pId]["left"] =pLeft;
                      }
                  })
            return JSON.stringify(aProcessData);
          }catch(e){
              return '';
          }
	},
	tabchange : function(obj,value) {
		$(obj).attr("class","choice")
		$(obj).siblings().attr("class","")
		$("#box").find("div:eq("+value+")").attr("class","show")
		$("#box").find("div:eq("+value+")").siblings().attr("class","tab-item")
	},
	onchange : function(obj,type) {
		var apid = $(obj).val();
		if(type=='auto_person'){
			$(".auto_person").hide();
			$("#auto_person_"+apid).show();
		}else{
			if(apid==1){
				$("#wf_mode_2").show();
			}else{
				$("#wf_mode_2").hide();
			}
		}
	},
	SetHeight : function() {
		var ifm= document.getElementById("iframepage");   
		var subWeb = document.frames ? document.frames["iframepage"].document : ifm.contentDocument;   
		if(ifm != null && subWeb != null) {
		   ifm.height = '100%';
		   ifm.width = '100%';
		}   
	},
	Ico : function(id=0) {
		var data = ['','',''];
		return data[id];
	}
}